package com.dex4d.ui.main.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.TextInputLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dex4d.BuildConfig;
import com.dex4d.R;
import com.dex4d.constants.IConstants;
import com.dex4d.core.AppToolBarBaseActivity;
import com.dex4d.core.http.DefaultTransformer;
import com.dex4d.core.http.JsonApiWrapper;
import com.dex4d.core.subscribers.ProgressSubscriber;
import com.dex4d.glide.GlideUtil;
import com.dex4d.model.HttpResult;
import com.dex4d.model.RequestParam;
import com.dex4d.model.User;
import com.dex4d.ui.main.model.CoinToken;
import com.dex4d.ui.main.model.Dex4dResult;
import com.dex4d.ui.main.model.Dex4dTrade;
import com.dex4d.ui.main.model.TokenContract;
import com.dex4d.ui.main.model.TokenDetail;
import com.dex4d.ui.main.model.TradeResult;
import com.dex4d.ui.main.model.TradeToken;
import com.dex4d.ui.main.socket.RPC;
import com.dex4d.ui.main.socket.Receipt;
import com.dex4d.ui.main.view.EditTextField;
import com.dex4d.ui.main.view.bar.BubbleSeekBar;
import com.dex4d.utils.Arith;
import com.dex4d.utils.BalanceUtils;
import com.dex4d.utils.BaseUtils;
import com.dex4d.utils.Commons;
import com.dex4d.utils.DecimalInputFilter;
import com.framework.bigdecimalutils.BigDecimalUtils;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.web3j.utils.Convert;
import org.web3j.utils.Numeric;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindColor;
import butterknife.BindView;
import butterknife.OnClick;


/**
 * 交易页面
 */
public class TradeActivity extends AppToolBarBaseActivity implements Commons.BUNDLE_KEYS {

    @BindView(R.id.btn_confirm)
    Button btnConfirm;

    @BindView(R.id.seek_bar)
    BubbleSeekBar bubbleSeekBar;

    @BindView(R.id.edit_amount_layout)
    TextInputLayout editAmountLayout;

    @BindView(R.id.edit_input_amount)
    EditTextField editInputAmount;

    @BindView(R.id.tv_token_balance)
    TextView tv_token_balance;

    @BindView(R.id.tv_d4d_balance)
    TextView tv_d4d_balance;

    @BindView(R.id.img_coin)
    ImageView img_coin;

    @BindView(R.id.txt_coin_name)
    TextView txt_coin_name;

    @BindView(R.id.trade_buy)
    TextView trade_buy;

    @BindView(R.id.trade_reinvest)
    TextView trade_reinvest;

    @BindView(R.id.trade_sell)
    TextView trade_sell;

    @BindView(R.id.trade_swap)
    TextView trade_swap;

    @BindView(R.id.label_volume)
    TextView label_volume;

    @BindView(R.id.label_gas)
    TextView label_gas;

    @BindView(R.id.label_balance)
    TextView label_balance;

    @BindView(R.id.label_in_contract)
    TextView label_in_contract;

    @BindView(R.id.txt_pending)
    TextView txt_pending;

    @BindView(R.id.ll_swap)
    LinearLayout ll_swap;

    @BindView(R.id.tv_swap_target_token)
    TextView tv_swap_target_token;

    @BindView(R.id.tv_d4d_amount_desc)
    TextView tv_d4d_amount_desc;

    @BindView(R.id.ll_to_trade)
    LinearLayout ll_to_trade;

    @BindView(R.id.ll_no_swap_auth)
    LinearLayout ll_no_swap_auth;

    @BindView(R.id.ry_call_popupwindow)
    RelativeLayout ry_call_popupwindow;

    @BindView(R.id.tv_state_remind)
    TextView tv_state_remind;

    private CoinToken coinToken;//上个页面传入值
    private List<String> mSwapList = new ArrayList<String>();

    Receipt receipt;

    //type  操作类型 ，具体类型值再 TradeResult.FLAG 中
    private int mType = TradeResult.FLAG_BUY;
    private String mWalletBalance = "0.0"; //钱包余额
    private BigInteger mGasPrice;
    private String mGasFee;
    private String mTokenContractAddress; //approve 使用
    private String mDealerContractAddress; //approve 使用
    private String mCoinAmount; //除了D4D的TOKEN数量，即买D4D需要消费的数量，卖D4D可得的数量

    public static void start(Activity activity, CoinToken coinToken, TokenDetail tokenDetail,ArrayList<CoinToken> tokenList) {
        Intent intent = new Intent(activity, TradeActivity.class);
        intent.putExtra("CoinToken", coinToken);
        intent.putExtra("TokenDetail", tokenDetail);
        intent.putParcelableArrayListExtra(Commons.BUNDLE_KEYS.ALL_TRADE_TOKEN, tokenList);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_trade;
    }

    //获取可对倒的交易池
//    private List<String> getSwapList(){
//        if(mSwapList == null || mSwapList.size()==0){
//            return new ArrayList<String>();
//        }else {
//            return mSwapList;
//        }
//    }

    Handler mHandler=new Handler();
    Runnable runnable=new Runnable() {
        @Override
        public void run() {
            loadStateAndTypeShow();
            mHandler.postDelayed(this, 1000);
        }
    };

    //根据货币状态显示不同的页面
    private void loadStateAndTypeShow(){
        TokenDetail tokenDetail = getIntent().getParcelableExtra("TokenDetail");

        if(tokenDetail.state == 0){
            tv_state_remind.setText(getString(R.string.dex4d_state_advisor_remind,BaseUtils.getCountdown(tokenDetail.ambassador_end)));
            tv_state_remind.setVisibility(View.VISIBLE);
            ll_to_trade.setVisibility(View.GONE);
            ll_no_swap_auth.setVisibility(View.GONE);
        }else if(mType == TradeResult.FLAG_SWAP){
            if(tokenDetail.state ==1){
                tv_state_remind.setText(getString(R.string.dex4d_state_new_remind));
                tv_state_remind.setVisibility(View.VISIBLE);
                ll_to_trade.setVisibility(View.GONE);
                ll_no_swap_auth.setVisibility(View.GONE);
            }else if(tokenDetail.state == 3){
                tv_state_remind.setText(getString(R.string.dex4d_state_down_remind,BaseUtils.getCountdown(tokenDetail.offline_time)));
                tv_state_remind.setVisibility(View.VISIBLE);
                ll_to_trade.setVisibility(View.GONE);
                ll_no_swap_auth.setVisibility(View.GONE);
            } else {
                tv_state_remind.setVisibility(View.GONE);
                //查询是否有对倒权限
                RequestParam requestParam = new RequestParam();
                requestParam.setId(8);
                requestParam.setMethod(IConstants.CONTRACTSERVICE_ISARBITRAGER);
                requestParam.setParams(Collections.singletonList(User.getInstance().getAddress()));
                JsonApiWrapper
                        .serviceApi()
                        .requestByParam(requestParam)
                        .compose(new DefaultTransformer<HttpResult<String>>())  //取网络数据这个函数不能少，这是线程切换
                        .subscribe(new ProgressSubscriber<HttpResult<String>>(this, false) {
                            @Override
                            public void onNext(HttpResult<String> result) {
                                //等于1时，有对倒权限
                                if(result.getResult().equals("1")){
                                    ll_to_trade.setVisibility(View.VISIBLE);
                                    ll_no_swap_auth.setVisibility(View.GONE);
                                }else {
                                    //无对倒权限
                                    ll_to_trade.setVisibility(View.GONE);
                                    ll_no_swap_auth.setVisibility(View.VISIBLE);
                                }
                            }});
            }
        }else {
            tv_state_remind.setVisibility(View.GONE);
            ll_to_trade.setVisibility(View.VISIBLE);
            ll_no_swap_auth.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initVariables() {
        mHandler.post(runnable);

        coinToken = getIntent().getParcelableExtra("CoinToken");
        //通证余额
        tv_token_balance.setText(getTokenBalance());
        //D4D余额
        tv_d4d_balance.setText(coinToken.dex4d);

        //供popupwindow 对倒使用
        tv_swap_target_token.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(s.length()>0) {
                    loadAmountInContract(s.toString());
                }
            }
        });

        receipt = new Receipt();
        receipt.send();

        GlideUtil.displayImg(img_coin,coinToken.logo);

        txt_coin_name.setText(coinToken.getShowSymbol());

        //监听输入
        editInputAmount.setFilters(new InputFilter[] {new DecimalInputFilter()}); //小数点6位
        editInputAmount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(s.length()>0 && !BigDecimalUtils.is(s.toString()).isNullOrZero()){
                    btnConfirm.setBackgroundResource(R.drawable.btn_blue_clickable_bg);
                    btnConfirm.setTextColor(getResources().getColor(R.color.white));
                    btnConfirm.setClickable(true);
                }else {
                    btnConfirm.setBackgroundResource(R.drawable.btn_blue_unclick_bg);
                    btnConfirm.setTextColor(getResources().getColor(R.color.gray_B7C5CA));
                    btnConfirm.setClickable(false);
                }

                if(mType==TradeResult.FLAG_BUY ||mType==TradeResult.FLAG_REINVEST) {
                    tradeBuy(s.length()>0? s.toString():"0.0");
                }else if(mType==TradeResult.FLAG_SELL || mType ==TradeResult.FLAG_SWAP){
                    tradeSell(s.length()>0? s.toString():"0.0");
                }
            }
        });

        bubbleSeekBar.setOnProgressChangedListener(new BubbleSeekBar.OnProgressChangedListenerAdapter() {
            @Override
            public void getProgressOnFinally(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat, boolean fromUser) {
                super.getProgressOnFinally(bubbleSeekBar, progress, progressFloat, fromUser);
            }

            @Override
            public void getProgressOnActionUp(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat) {
                super.getProgressOnActionUp(bubbleSeekBar, progress, progressFloat);
                if(mType==TradeResult.FLAG_BUY ||mType==TradeResult.FLAG_REINVEST) {
                    tradeBuy(progress);
                }else if(mType==TradeResult.FLAG_SELL || mType ==TradeResult.FLAG_SWAP){
                    tradeSell(progress);
                }
            }
        });

//        KeyboardPopHelper.instance(this)
//                .bindEditText(editInputAmount)              // 绑定目标edittext
//                .bindRootView(findViewById(R.id.root_view))        // 绑定页面根布局
//                .setMonitorFocusSizeChanged(true)                   // 是否监控focusView高度的变化
//                .setBottomMargin(10)                                // focusView的bottom
//                .setOffset(-100)                                    // 固定模式下的偏移
//                .monitor();

        //设置购买
        buyClick();
    }

    //获取通证余额
    private String getTokenBalance(){
        double total = 0;
        if(coinToken!=null){
            //可变现资产、交易分红、推荐分红相加
            total = Arith.add(Double.parseDouble(coinToken.coins),Double.parseDouble(coinToken.dividends));
            total = Arith.add(total,Double.parseDouble(coinToken.rebateFees));
        }
        return BalanceUtils.format(total + "");
    }

    @Override
    protected void loadData() {

        //请求此接口获取token列表
        final RequestParam requestParam2 = new RequestParam();
        requestParam2.setId(1);
        requestParam2.setJsonrpc(IConstants.JSON_RPC_VERSION);
        requestParam2.setMethod(IConstants.GATEWAY_GETTOKENTABLES);
        requestParam2.setParams(new ArrayList<String>());

        JsonApiWrapper
                .serviceApi()
                .getTokenTables(requestParam2)
                .compose(new DefaultTransformer<HttpResult<List<TokenContract>>>())
                .subscribe(new ProgressSubscriber<HttpResult<List<TokenContract>>>(this, false) {
                    @Override
                    public void onNext(HttpResult<List<TokenContract>> result) {
                        for (TokenContract temp : result.getResult()) {
                            if (TextUtils.equals(coinToken.symbol, temp.name)) {
                                if (TextUtils.equals(coinToken.symbol, Dex4dTrade.ETH)) {
                                    mDealerContractAddress = temp.dealer_addr;
                                    mTokenContractAddress = BuildConfig.CONTRACT_DEX4D_PROTOCOL;
                                } else {
                                    mDealerContractAddress = temp.dealer_addr;
                                    mTokenContractAddress = temp.token_addr;
                                }

                                loadAssetInfo(coinToken.symbol, temp.token_addr); //加载资产余额信息
                            }else if(temp.state == 2){
                                mSwapList.add(temp.name);
                            }
                        }
                        if(mSwapList.size()>0){
                            tv_swap_target_token.setText(mSwapList.get(0).toUpperCase());
                        }else {
                            tv_swap_target_token.setOnClickListener(null);
                        }

                    }
                });

        final RequestParam gasParam = new RequestParam();
        gasParam.setId(2);
        gasParam.setJsonrpc(IConstants.JSON_RPC_VERSION);
        gasParam.setMethod(IConstants.CONTRACTSERVICE_GASPRICE);
        gasParam.setParams(Collections.singletonList(User.getInstance().getAddress()));

        //gas price
        JsonApiWrapper
                .serviceApi()
                .requestByParam(gasParam)
                .compose(new DefaultTransformer<HttpResult<String>>())  //取网络数据这个函数不能少，这是线程切换
                .subscribe(new ProgressSubscriber<HttpResult<String>>(this, false) {
                    @Override
                    public void onNext(HttpResult<String> result) {
                        //服务器传过来的 GasPrice 是十进制
                        mGasPrice =  new BigInteger(result.getResult());
                        //默认设置为Buy的gas费用
                        mGasFee = calculateGasFee(TradeResult.FLAG_BUY);
                        label_gas.setText(getString(R.string.trade_label_gas_consumption,mGasFee));
                    }
                });
    }

    private String calculateGasFee(int limitFlag){
        if(mGasPrice == null)
            return "0.0";

        BigInteger gasLimit = Numeric.toBigInt(Dex4dTrade.getHexGasLimit(limitFlag));
        return Convert.fromWei(mGasPrice.multiply(gasLimit).toString(), Convert.Unit.ETHER).setScale(6, RoundingMode.CEILING).toString();
    }

    //加载合约里有可 兑换/对倒 的余额
    private void loadAmountInContract(final String symbol){
        final RequestParam requestParam = new RequestParam();
        requestParam.setId(3);
        requestParam.setJsonrpc(IConstants.JSON_RPC_VERSION);
        requestParam.setMethod(IConstants.MARKET_GETMARKETCAPINFO);
        List<String> list = new ArrayList<>();
        list.add(symbol.toLowerCase());
        requestParam.setParams(list);

        JsonApiWrapper
                .serviceApi()
                .getMarketCapInfo(requestParam)
                .compose(new DefaultTransformer<HttpResult<Dex4dResult<TradeToken>>>())  //取网络数据这个函数不能少，这是线程切换
                .subscribe(new ProgressSubscriber<HttpResult<Dex4dResult<TradeToken>>>(this, false) {
                    @Override
                    public void onNext(HttpResult<Dex4dResult<TradeToken>> result) {
                        TradeToken tradeToken = result.getResult().data;
                        String totalSupply = Convert.fromWei(tradeToken.total_supply, Convert.Unit.ETHER).setScale(6, RoundingMode.CEILING).toString();
                        label_in_contract.setText(getString(R.string.trade_label_in_contract,symbol.toUpperCase(),totalSupply,symbol.toUpperCase()));
                    }
                });
    }

    //加载资产余额信息
    private void loadAssetInfo(final String symbol, String contractAddress) {
        RequestParam requestParam = new RequestParam();
        requestParam.setId(4);
        requestParam.setJsonrpc(IConstants.JSON_RPC_VERSION);
        if (IConstants.ETH_SYMBOL.equalsIgnoreCase((symbol))) {
            //查询以太余额调用此接口
            requestParam.setMethod(IConstants.CONTRACTSERVICE_GETBALANCE);
            requestParam.setParams(Collections.singletonList(User.getInstance().getAddress()));
        } else {
            //查询其他代币余额调用此接口
            requestParam.setMethod(IConstants.CONTRACTSERVICE_ERC20BALANCE);
            List<String> paramsList = new ArrayList<String>();
            paramsList.add(contractAddress);
            paramsList.add(User.getInstance().getAddress());
            requestParam.setParams(paramsList);
        }
        JsonApiWrapper
                .serviceApi()
                .requestByParam(requestParam)
                .compose(new DefaultTransformer<HttpResult<String>>())  //取网络数据这个函数不能少，这是线程切换
                .subscribe(new ProgressSubscriber<HttpResult<String>>(this, false) {
                    @Override
                    public void onNext(HttpResult<String> result) {
                        String balance = BaseUtils.hexToEtherUnit(result.getResult()); //unit ether
                        mWalletBalance = balance;
                        //底部展示信息
                        label_balance.setText(String.format(getResources().getString(R.string.trade_label_wallet_balance),
                                mWalletBalance,
                                coinToken.getShowSymbol()));
                    }
                });
    }

    @Override
    protected void initToolbar() {
        showBackView();
        String title=getResources().getString(R.string.dex4d_trade_title);
        showTitle(title);
    }

    /**
     * 购买(拖动进度条)
     *
     * @param progress 根据进度计算花费的代币数量
     */
    void tradeBuy(int progress) {
        final RequestParam requestParam = new RequestParam();
        requestParam.setId(5);
        requestParam.setJsonrpc(IConstants.JSON_RPC_VERSION);
        requestParam.setMethod(IConstants.CONTRACTSERVICE_CALCULATETOKENSRECEIVED);

        List<String> list = new ArrayList<>();
        list.add(coinToken.symbol);

        //TODO 根据进度计算，保留6位小数
        BigDecimal b1 = new BigDecimal(mWalletBalance);
        if(mType == TradeResult.FLAG_REINVEST){
            b1 = new BigDecimal(coinToken.dividends);
        }

        BigDecimal b2 = new BigDecimal(progress).divide(new BigDecimal(100));

        mCoinAmount = b1.multiply(b2).setScale(6, RoundingMode.CEILING).toString(); //(10进制) 准备消耗多少资金去购买DEX4D
        list.add(mCoinAmount);
        requestParam.setParams(list);

        JsonApiWrapper
                .serviceApi()
                .calculateTokensReceived(requestParam)
                .compose(new DefaultTransformer<HttpResult<String>>())  //取网络数据这个函数不能少，这是线程切换
                .subscribe(new ProgressSubscriber<HttpResult<String>>(this, false) {
                    @Override
                    public void onNext(HttpResult<String> result) {
                        //此处拿到的是可以获得的Dex4D的数量 16进制

                        editInputAmount.setText(BaseUtils.hexToEtherUnit(result.getResult()));
                        label_volume.setText(getString(R.string.trade_label_total_volume, mCoinAmount, coinToken.getShowSymbol()));//数量
                    }
                });
    }

    /**
     * 购买(自己填写)
     *
     * @param tokenAmount Dex4D的买入数量(10进制)
     */
    void tradeBuy(final String tokenAmount) {
        final RequestParam requestParam = new RequestParam();
        requestParam.setId(6);
        requestParam.setJsonrpc(IConstants.JSON_RPC_VERSION);
        requestParam.setMethod(IConstants.CONTRACTSERVICE_CALCULATEBUYTOKENSPEND);
        List<String> list = new ArrayList<>();
        list.add(coinToken.symbol);
        list.add(new BigDecimal(tokenAmount).setScale(6, RoundingMode.CEILING).toString());
        requestParam.setParams(list);

        JsonApiWrapper
                .serviceApi()
                .calculateBuyTokenSpend(requestParam)
                .compose(new DefaultTransformer<HttpResult<String>>())  //取网络数据这个函数不能少，这是线程切换
                .subscribe(new ProgressSubscriber<HttpResult<String>>(this, false) {
                    @Override
                    public void onNext(HttpResult<String> resultHex) {
                        //此处拿到结果的是花费的代币数量 (16进制)

                        //计算花费的代币(将结果转10进制)
                        String value = Numeric.decodeQuantity(resultHex.getResult()).toString();
                        mCoinAmount = Convert.fromWei(value, Convert.Unit.ETHER).setScale(6, RoundingMode.CEILING).toString();

                        //进度计算
                        BigDecimal b1 = new BigDecimal(mWalletBalance);
                        if(mType == TradeResult.FLAG_REINVEST){
                            b1 = new BigDecimal(coinToken.dividends);
                        }
                        BigDecimal b2 = new BigDecimal(mCoinAmount);//需要花费
                        if(b1.doubleValue() > 0) {
                            final double percent = b2.divide(b1, 4, RoundingMode.CEILING).multiply(new BigDecimal(100)).setScale(2, RoundingMode.CEILING).doubleValue();
                            if (percent > 100) {
                                bubbleSeekBar.setProgress(100);
                            } else {
                                bubbleSeekBar.setProgress((float) percent);
                            }
                        }

                        label_volume.setText(getString(R.string.trade_label_total_volume, mCoinAmount, coinToken.getShowSymbol()));//数量
                    }
                });
    }

    //根据输入的数量计算进度条,计算可卖出多少币
    private void tradeSell(final String dex4dAmount) {
        String totalDex4dAmount = coinToken.dex4d;
        try {
            int progress  = (int)(Arith.div(Double.parseDouble(dex4dAmount),
                    Double.parseDouble(totalDex4dAmount),2) * 100);
            if(progress >= 100){
                bubbleSeekBar.setProgress(100);
            }else {
                bubbleSeekBar.setProgress((float) progress);
            }
        }catch (Exception e){

        }

        //调用接口计算卖出D4D可得多少token
        calculateSellAvailableAmount();
    }

    //根据进度条计算输入框的值,同时计算可卖出多少币
    private void tradeSell(final int progress) {
        String totalDex4dAmount = coinToken.dex4d;

        try{
            String sellD4dAmount = Arith.mul(Double.parseDouble(totalDex4dAmount),
                    Arith.div(progress,100,2),6) + "";
            editInputAmount.setText(sellD4dAmount);
        }catch (Exception e){

        }
    }

    //调用接口计算卖出D4D可得多少token
    private void calculateSellAvailableAmount(){
        final RequestParam requestParam = new RequestParam();
        requestParam.setId(7);
        requestParam.setJsonrpc(IConstants.JSON_RPC_VERSION);
        requestParam.setMethod(IConstants.CONTRACTSERVICE_CALCULATEBUYTOKENRECEIVED);
        List<String> paramList = new ArrayList<>();
        if(mType==TradeResult.FLAG_SELL){
            //sell
            paramList.add(coinToken.symbol);
        }else if(mType ==TradeResult.FLAG_SWAP){
            if(!tv_swap_target_token.hasOnClickListeners()){
                //没有可对倒的币种，退出
                return;
            }
            //对倒
            paramList.add(tv_swap_target_token.getText().toString().toLowerCase());
        }
        String d4dAmount = editInputAmount.getText().toString();
        if(TextUtils.isEmpty(d4dAmount)){
            d4dAmount = "0.0";
        }
        paramList.add(d4dAmount);
        requestParam.setParams(paramList);
        JsonApiWrapper
                .serviceApi()
                .requestByParam(requestParam)
                .compose(new DefaultTransformer<HttpResult<String>>())  //取网络数据这个函数不能少，这是线程切换
                .subscribe(new ProgressSubscriber<HttpResult<String>>(this, false) {
                    @Override
                    public void onNext(HttpResult<String> result) {
                        String amount = BaseUtils.hexToEtherUnit(result.getResult()); //unit ether
                        mCoinAmount = amount; //10进制
                        if(mType==TradeResult.FLAG_SELL){
                            //sell
                            label_volume.setText(getString(R.string.trade_label_total_volume,amount,coinToken.getShowSymbol()));
                        }else if(mType ==TradeResult.FLAG_SWAP){
                            //对倒
                            label_volume.setText(getString(R.string.trade_label_total_volume,amount,tv_swap_target_token.getText().toString().toUpperCase()));
                        }
                    }});
    }

    @BindColor(R.color.account_token_txt_price)
    int tradeNormal;

    @BindColor(R.color.white)
    int tradeSelected;

    @OnClick(R.id.trade_buy)
    void buyClick() {
        mType = TradeResult.FLAG_BUY;
        loadStateAndTypeShow();

        //交易页面打开，无权限页面关闭
//        ll_to_trade.setVisibility(View.VISIBLE);
//        ll_no_swap_auth.setVisibility(View.GONE);

        //对倒的页签布局关掉
        ll_swap.setVisibility(View.GONE);
        tv_d4d_amount_desc.setVisibility(View.VISIBLE);

        //底部显示的项
        editInputAmount.setText("0");
        mGasFee = calculateGasFee(TradeResult.FLAG_BUY);
        label_volume.setText(getString(R.string.trade_label_total_volume,"0.000000",coinToken.getShowSymbol())); //volume
        label_gas.setText(getString(R.string.trade_label_gas_consumption,mGasFee)); //buy gas
        label_balance.setText(getString(R.string.trade_label_wallet_balance,mWalletBalance,coinToken.getShowSymbol())); //wallet balance
        label_in_contract.setVisibility(View.GONE);

        trade_buy.setTextColor(tradeSelected);
        trade_reinvest.setTextColor(tradeNormal);
        trade_sell.setTextColor(tradeNormal);
        trade_swap.setTextColor(tradeNormal);
        trade_buy.setTextSize(18);
        trade_reinvest.setTextSize(16);
        trade_sell.setTextSize(16);
        trade_swap.setTextSize(16);

        bold(trade_swap, false);
        bold(trade_buy, true);
        bold(trade_reinvest, false);
        bold(trade_sell, false);
    }


    @OnClick(R.id.trade_reinvest)
    void reinvestClick() {
        mType = TradeResult.FLAG_REINVEST;
        loadStateAndTypeShow();

        //交易页面打开，无权限页面关闭
//        ll_to_trade.setVisibility(View.VISIBLE);
//        ll_no_swap_auth.setVisibility(View.GONE);

        //对倒的页签布局关掉
        ll_swap.setVisibility(View.GONE);
        tv_d4d_amount_desc.setVisibility(View.VISIBLE);

        //底部显示的项
        editInputAmount.setText("0");
        mGasFee = calculateGasFee(TradeResult.FLAG_REINVEST);
        label_volume.setText(getString(R.string.trade_label_total_volume,"0.000000",coinToken.getShowSymbol())); //volume
        label_gas.setText(getString(R.string.trade_label_gas_consumption,mGasFee)); //reinvest gas
        label_balance.setText(getString(R.string.trade_label_total_dividends,coinToken.dividends,coinToken.getShowSymbol())); //total dividends
        label_in_contract.setVisibility(View.GONE);


        trade_buy.setTextColor(tradeNormal);
        trade_reinvest.setTextColor(tradeSelected);
        trade_sell.setTextColor(tradeNormal);
        trade_swap.setTextColor(tradeNormal);

        trade_buy.setTextSize(16);
        trade_reinvest.setTextSize(18);
        trade_sell.setTextSize(16);
        trade_swap.setTextSize(16);

        bold(trade_swap, false);
        bold(trade_buy, false);
        bold(trade_reinvest, true);
        bold(trade_sell, false);
    }

    @OnClick(R.id.trade_sell)
    void sellClick() {
        mType = TradeResult.FLAG_SELL;
        loadStateAndTypeShow();

        //交易页面打开，无权限页面关闭
//        ll_to_trade.setVisibility(View.VISIBLE);
//        ll_no_swap_auth.setVisibility(View.GONE);

        //对倒的页签布局关掉
        ll_swap.setVisibility(View.GONE);
        tv_d4d_amount_desc.setVisibility(View.VISIBLE);

        //底部显示的项
        editInputAmount.setText("0");
        mGasFee = calculateGasFee(TradeResult.FLAG_SELL);
        label_volume.setText(getString(R.string.trade_label_total_volume,"0.000000",coinToken.getShowSymbol())); //volume
        label_gas.setText(getString(R.string.trade_label_gas_consumption,mGasFee)); //sell gas
        label_balance.setText(getString(R.string.trade_label_d4d_balance,coinToken.dex4d)); //d4d balance
        label_in_contract.setVisibility(View.GONE);


        trade_buy.setTextColor(tradeNormal);
        trade_reinvest.setTextColor(tradeNormal);
        trade_sell.setTextColor(tradeSelected);
        trade_swap.setTextColor(tradeNormal);

        trade_buy.setTextSize(16);
        trade_reinvest.setTextSize(16);
        trade_sell.setTextSize(18);
        trade_swap.setTextSize(16);

        bold(trade_swap, false);
        bold(trade_buy, false);
        bold(trade_reinvest, false);
        bold(trade_sell, true);
    }

    @OnClick({R.id.trade_swap})
    void swapClick() {
        mType = TradeResult.FLAG_SWAP;
        loadStateAndTypeShow();

        //对倒的页签布局开启
        ll_swap.setVisibility(View.VISIBLE);
        tv_d4d_amount_desc.setVisibility(View.GONE);

        //底部显示的项
        editInputAmount.setText("0");
        mGasFee = calculateGasFee(TradeResult.FLAG_SWAP);
        label_volume.setText(getString(R.string.trade_label_total_volume,"0.000000",coinToken.getShowSymbol())); //volume
        label_gas.setText(getString(R.string.trade_label_gas_consumption,mGasFee)); //swap gas
        label_balance.setText(getString(R.string.trade_label_d4d_balance,coinToken.dex4d)); //d4d balance
        label_in_contract.setVisibility(View.VISIBLE);

        trade_buy.setTextColor(tradeNormal);
        trade_reinvest.setTextColor(tradeNormal);
        trade_sell.setTextColor(tradeNormal);
        trade_swap.setTextColor(tradeSelected);

        trade_buy.setTextSize(16);
        trade_reinvest.setTextSize(16);
        trade_sell.setTextSize(16);
        trade_swap.setTextSize(18);
        bold(trade_swap, true);
        bold(trade_buy, false);
        bold(trade_reinvest, false);
        bold(trade_sell, false);

    }

    private void bold(TextView tv, boolean isBold) {
        TextPaint tp = tv.getPaint();
        tp.setFakeBoldText(true);
    }

    @OnClick({R.id.ry_call_popupwindow})
    void onCallPopupwindow(){
        showPopWindow();
    }

    @OnClick(R.id.btn_confirm)
    void tradeConfirm() {
        Bundle bundle = new Bundle();
        bundle.putInt(TRADE_TYPE,mType);
        bundle.putString(POOL_SYMBOL,coinToken.symbol);
        bundle.putString(DEALER_CONTRACT_ADDRESS,mDealerContractAddress); //approve 使用
        bundle.putString(TOKEN_CONTRACT_ADDRESS,mTokenContractAddress); //approve 使用
        bundle.putString(TO_SYMBOL,tv_swap_target_token.getText().toString());
        bundle.putString(D4D_AMOUNT,editInputAmount.getText().toString()); //d4d数量
        bundle.putString(COIN_AMOUNT,mCoinAmount); //花费或得到的代币数量
        bundle.putString(GAS_CONSUMPTION,mGasFee);
        openActivity(TradeConfirmActivity.class,bundle);
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    public void updatePending(RPC rpc) {
        receipt.updateUI(rpc, coinToken.symbol, txt_pending);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacks(runnable);
        //取消订阅状态
        receipt.stop();
        EventBus.getDefault().unregister(this);
    }

    private void showPopWindow() {
        View rootView = findViewById(R.id.root_view); // 當前頁面的根佈局
        View contentView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.popupwindow, null);
        final PopupWindow popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT,true);

        if(!mSwapList.contains("cancel")){
            mSwapList.add("cancel");
        }

        RecyclerView rv_tokens = contentView.findViewById(R.id.rv_tokens);
        rv_tokens.setAdapter(new CommonAdapter<String>(this, R.layout.item_popupwindow, mSwapList) {
            @Override
            protected void convert(ViewHolder holder, final String tokenName, final int position) {
                holder.setText(R.id.tv_token_name, tokenName.toUpperCase());
                holder.setOnClickListener(R.id.tv_token_name, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(position != mSwapList.size()-1) {
                            tv_swap_target_token.setText(tokenName.toUpperCase());
                            editInputAmount.setText("0");
                        }
                        popupWindow.dismiss();
                    }
                });
            }
        });

        rv_tokens.setLayoutManager(new LinearLayoutManager(this));
        rv_tokens.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this)
                .color(getResources().getColor(R.color.gray))
                .build());

        setBackgroundAlpha(0.3823f);//设置屏幕透明度
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // popupWindow隐藏时恢复屏幕正常透明度
                setBackgroundAlpha(1.0f);
            }
        });
        popupWindow.showAtLocation(rootView, Gravity.BOTTOM | Gravity.CENTER, 0, 0);
    }

    /** * 设置添加屏幕的背景透明度 * */
    private void setBackgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha;
        getWindow().setAttributes(lp);
    }
}
